module ModelHelper
    
    public  
    
    ##########################################################
    # Generate a where clause from a list of terms using AND
    def make_and_sql_where(field, terms, wildcards='')
        #terms.collect {|term| sanitize_sql( ["#{field} LIKE ?", term])}.join(" AND ")
        where_sql = "LOWER(" + field + ") LIKE '" + wildcards
        where_sql << terms.inject("") {	|str, term| 
            str << wildcards + "' AND LOWER(" + field + ") LIKE '" + wildcards unless str.empty?
            str << term.downcase.gsub(/\\/, '\&\&').gsub(/'/, "''")
        }
        where_sql << wildcards + "' "        
    end
    
    
       
    ##########################################################
    # Cleans and quotes an sql item
    def clean_sql(item)
        connection.quote(item)
    end
    
    def add_limit!(sql, options = {})
        if limit = options[:limit]
            sql << " LIMIT #{limit}"
            if offset = options[:offset]
                sql << " OFFSET #{offset}"
            end
        end
    end
        
    ##########################################################
    # Calculates the number of days ago that an event occured
    def days_ago(days)
     (Time.now-(60*60*24*days)).strftime("%Y-%m-%dT%H:%M:%S")
    end
    
    module_function :days_ago
    module_function :make_and_sql_where
    module_function :add_limit!
end